package com.example.demo.service.impl;

import com.example.demo.common.Result;
import com.example.demo.dto.VehicleCreateDTO;
import com.example.demo.dto.VehicleGetDTO;
import com.example.demo.entity.Vehicle;
import com.example.demo.mapper.VehicleMapper;
import com.example.demo.service.VehicleService;
import com.example.demo.vo.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class VehicleServiceImpl implements VehicleService {
    @Autowired
    private VehicleMapper vehicleMapper;
    @Override
    public Result searchVehicleByIdAndType(VehicleGetDTO vehicleGetDTO) {
        String id = null;
        String type = null;
        if(vehicleGetDTO.getId()!=null && !vehicleGetDTO.getId().equals("")){
            id = vehicleGetDTO.getId();
        }
        if(vehicleGetDTO.getType()!=null && !vehicleGetDTO.getType().equals("")){
            type = vehicleGetDTO.getType();
        }
        List<Vehicle> vehicleList = vehicleMapper.selectVehicleByIdAndType(id, type);
        ResponseData<Vehicle> responseData = new ResponseData<>();
        responseData.setList(vehicleList);
        responseData.setTotal(vehicleList.size());
        return Result.success(responseData);
    }

    @Override
    public Result getAllCarIds() {
        List<String> ids = vehicleMapper.selectAllIds();
        return Result.success(ids);
    }

    @Transactional
    @Override
    public Result batDelete(String[] ids) {
        for(String id : ids){
//            System.out.println("currentId:"+id);
            vehicleMapper.deleteVehicle(id);
        }
        return Result.success();
    }

    @Override
    public Result deleteVehicleById(String id) {
        int aff = vehicleMapper.deleteVehicle(id);
        if(aff>0){
            return Result.success();
        }else{
            return Result.fail();
        }
    }

    @Override
    public Result addVehicle(VehicleCreateDTO vehicleCreateDTO) {
        Vehicle vehicle = new Vehicle();
        System.out.println(vehicleCreateDTO);
        vehicle.setId(vehicleCreateDTO.getId());
        vehicle.setType(vehicleCreateDTO.getType());
        vehicle.setSeats(vehicleCreateDTO.getSeats());
        LocalDate localDate =LocalDate.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        vehicle.setCreateTime(dtf.format(localDate));
        int aff = vehicleMapper.insertVehicle(vehicle);
        if(aff>0){
            return Result.success();
        }else{
            return Result.fail();
        }
    }
}
